<template>
  <div class="app-container image">
    <div class="image-header">
      <span class="header-title">集群：</span>
      <el-select v-model="selCluster" placeholder="请选择集群" @change="handleSelCluster">
        <el-option
          v-for="item in clusterOptions"
          :key="item.ip"
          :label="item.name"
          :value="item.name" />
      </el-select>
      <div class="header-title-left"><el-button type="primary" size="mini" @click="dialog.createSource = true">新建数据集</el-button></div>
    </div>
    <el-table
      :data="list"
      style="width: 100%">
      <el-table-column
        label="ID"
        width="120">
        <template slot-scope="scope">
          <div class="table-link">
            <span @click="toDetail(scope.row)">{{ scope.row.id }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="Name">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="type"
        label="Type">
        <template slot-scope="scope">
          <span>{{ scope.row.type ? scope.row.type : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="place"
        label="Path">
        <template slot-scope="scope">
          <span>{{ scope.row.place }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="size"
        label="Provider">
        <template slot-scope="scope">
          <span>{{ scope.row.provider ? scope.row.provider : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="startTime"
        label="CreateTime">
        <template slot-scope="scope">
          <span>{{ scope.row.createtime ? new Date(Date.parse(new Date(scope.row.createtime))).Format("yyyy-MM-dd hh:mm:ss") : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <a class="table-action" @click="clickUpdateSource(scope.row)">编辑</a>
          <a class="table-action" @click="clickDeleteSource(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialog.createSource"
      :title="dialog.editSource ? '编辑数据集' : '新建数据集'"
      width="800px"
      @close="resetForm('createSourceForm')">
      <el-form ref="createSourceForm" :model="createSourceForm" :rules="rulesCreateSource" label-width="110px">
        <el-form-item v-if="!dialog.editSource" label="ID" prop="id">
          <el-input v-model="createSourceForm.id" />
        </el-form-item>
        <el-form-item label="数据集名称：" prop="name">
          <el-input v-model="createSourceForm.name" />
        </el-form-item>
        <el-form-item label="Type：" prop="type">
          <el-input v-model="createSourceForm.type" />
        </el-form-item>
        <el-form-item label="Path" prop="path">
          <el-input v-model="createSourceForm.path" />
        </el-form-item>
        <el-form-item label="Provider：" prop="provider">
          <el-input v-model="createSourceForm.provider" />
        </el-form-item>
      </el-form>
      <markdown-editor
        ref="markdownEditor"
        v-model="content"
        :options="{hideModeSwitch:true}"
        height="300px"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.createSource = false; dialog.editSource = false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('createSourceForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getClusterList } from '@/api/cluster'
import { getSourceList, deleteSource, handleSource } from '@/api/source'
import MarkdownEditor from '@/components/MarkdownEditor'

export default {
  components: { MarkdownEditor },
  data() {
    return {
      list: null,
      listLoading: true,
      selCluster: '',
      clusterOptions: [],
      dialog: {
        createSource: false,
        editSource: false
      },
      createSourceForm: {
        id: '',
        name: '',
        type: '',
        path: '',
        provider: ''
      },
      rulesCreateSource: {
        id: [
          { required: true, message: '请输入镜像ID', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入数据集名称', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入数据集路径', trigger: 'blur' }
        ]
      },
      content: ''
    }
  },
  created() {
    this._fetchClusterData()
  },
  methods: {
    // 点击table名称
    toDetail(row) {
      this.$store.dispatch('SaveCurSource', row.description)
      this.$router.push({ path: '/source/detail' })
    },
    // 选择集群
    handleSelCluster(val) {
      this.list = []
      this._fetchDataSetData(val)
    },
    // 点击删除资源
    clickDeleteSource(row) {
      this.$confirm('此操作将删除该数据集, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._deleteSource(row)
      })
    },
    // 表单提交(createSourceForm: 新建数据集)
    submitForm() {
      const method = this.dialog.editSource ? 'UPDATE' : 'ADD'
      const msgText = this.dialog.editSource ? '编辑' : '新建'
      this.$refs['createSourceForm'].validate((valid) => {
        if (valid) {
          this._handleSource(method, msgText)
          this.dialog.createSource = false
          this.resetForm('createSourceForm')
        } else {
          return false
        }
      })
    },
    // 编辑资源
    clickUpdateSource(row) {
      this.dialog.editSource = true
      this.dialog.createSource = true
      this.curEditRow = row
      this.createSourceForm = {
        name: row.name,
        type: row.type,
        path: row.place,
        provider: row.provider
      }
      this.$nextTick(() => {
        this.$refs.markdownEditor.setHtml(row.description)
      })
    },
    // 重置表单
    resetForm(formName) {
      this.dialog.editSource = false
      this.createSourceForm = {
        name: '',
        type: '',
        path: '',
        provider: ''
      }
      this.$refs[formName].resetFields()
    },
    // 查询集群列表
    _fetchClusterData() {
      this.listLoading = true
      getClusterList().then(res => {
        if (res.message.code === 0) {
          this.listLoading = false
          this.clusterOptions = res.data.clusters_info
          if (this.clusterOptions.length > 0) {
            this._fetchDataSetData(this.clusterOptions[0].name)
            this.selCluster = this.clusterOptions[0].name
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 查询数据集列表
    _fetchDataSetData(clusterName) {
      this.listLoading = true
      const param = `${clusterName}/datasets_detail`
      getSourceList(param).then(res => {
        if (res.message.code === 0) {
          this.listLoading = false
          this.list = res.data
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 资源操作
    _handleSource(action, msgText = '新建') {
      const param = `${this.selCluster}/datasets_detail`
      let data = {}
      if (this.dialog.editSource) {
        data = {
          'action': action,
          'record': {
            'primary': {
              'name': 'id',
              'value': this.curEditRow.id
            },
            'content': {
              'name': this.createSourceForm.name,
              'place': this.createSourceForm.path,
              'provider': this.createSourceForm.provider,
              'type': this.createSourceForm.type,
              'description': this.$refs.markdownEditor.getValue()
            }
          }
        }
      } else {
        data = {
          'action': action,
          'record': {
            'id': this.createSourceForm.id,
            'name': this.createSourceForm.name,
            'place': this.createSourceForm.path,
            'provider': this.createSourceForm.provider,
            'type': this.createSourceForm.type,
            'createtime': Date.now(),
            'description': this.$refs.markdownEditor.getValue()
          }
        }
      }
      handleSource(param, data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: `${msgText}数据集成功`, showClose: true, type: 'success' })
          this._fetchDataSetData(this.selCluster)
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 删除数据集
    _deleteSource(row) {
      const param = `${this.selCluster}/datasets_detail`
      const data = {
        'action': 'DELETE',
        'record': {
          'id': row.id
        }
      }
      deleteSource(param, data).then(res => {
        if (res.message.code === 0) {
          this._fetchDataSetData(this.selCluster)
          this.$message({ message: '数据集删除成功', showClose: true, type: 'success' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.image {
  &-header {
    padding-bottom: 10px;
    .header-title {
      font-size: 14px;
      font-weight: 700;
    }
    .header-title-left {
      float: right;
      height: 40px;
      line-height: 40px;
    }
  }
  label {
    font-weight: normal
  }
  .table-action {
    color: #4285f4;
  }
  .table-link {
    color: #4285f4;
    &:hover {
      cursor: pointer;
    }
  }
  .status-box {
    border-radius: 5px;
    padding: 0 5px;
    color: #000000;
  }
  .status-success {
    background: #63D4AD;
  }
  .status-run {
    background: #85D8F7;
  }
  .status-wait {
    background: #f39c12;
  }
  .status-stop {
    background: #E0E3E8;
  }
  .status-failure {
    background: #F87D8D
  }
}
</style>
